﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using Microsoft.AspNet.SignalR;
using UploaderData;
using UploaderModels;
using UploaderWebApi.Models;

namespace UploaderWebApi.Controllers
{
    public class ImageUploadController : ApiController
    {
        [ActionName("upload-image")]
        public async Task<IHttpActionResult> PostUploadImage()
        {
            var db = new UploaderContext();


            var httpRequest = HttpContext.Current.Request;

            int imageId = 0;

            foreach (string file in httpRequest.Files)
            {
                var postedFile = httpRequest.Files[file];

                if (postedFile != null)
                {
                    using (var binaryReader = new BinaryReader(postedFile.InputStream))
                    {
                        var userImageByteArray = binaryReader.ReadBytes(postedFile.ContentLength);
                        var image = new ImageModel() { ImageBytes = userImageByteArray };
                        db.ImageModels.Add(image);
                        await db.SaveChangesAsync();
                        imageId = image.Id;
                    }
                }
            }


            if (httpRequest.Files.Count != 0)
            {
                var context = GlobalHost.ConnectionManager.GetHubContext<ImageHub>();
                var imgDb = db.ImageModels.Find(imageId);

                var lastSavedImage = new ReturnedImageModel()
                {
                    Id = imgDb.Id,
                    ImageBytes = imgDb.ImageBytes,
                };

                context.Clients.All.sendImages(lastSavedImage);
                return Ok("Image Saved To Database");
            }
            return InternalServerError();
        }


        [ActionName("get-images")]
        public HttpResponseMessage GetImages()
        {
            var db = new UploaderContext();
            HttpResponseMessage result = null;

            if (db.ImageModels.Count() != 0)
            {
                IEnumerable<ReturnedImageModel> imageList = ControllerHelper.CreateImageList(db.ImageModels);
                result = Request.CreateResponse(HttpStatusCode.Created, imageList);
            }
            else
            {
                result = Request.CreateResponse(HttpStatusCode.BadRequest);
            }
            return result;
        }
    }
}
